import vkey from 'vkey';

import throttle from '../../../../utils/throttle';
import scssVariables from './variables.scss';

const log = window.electron.log;

export const initPeerControl = (cb) => {
  window.electron.onNewTab(cb);
  const emitRobotCommand = window.electron.emitRobotCommand;

  const video = document.getElementById('screen-video');
  const video_container = document.querySelector('#screen-video-container');

  const getVideoBoundingClientRect = () => {
    const rect = video.getBoundingClientRect();
    return {
      width: rect.width,
      height: rect.height
    }
  };
  const getMousePosition = (e) => {
    return {
      pageX: e.pageX + video_container.scrollLeft,
      pageY: e.pageY - parseInt(scssVariables.toolbarHeight) + video_container.scrollTop
    }
  };

  //按键
  window.onkeydown = function (e) {
    log('window.onkeydown---:', e);
    log('vkey[data.keyCode].toLowerCase():',vkey[e.keyCode].toLowerCase());
    const data = {
      keyCode: e.keyCode,
      shift: e.shiftKey,
      meta: e.metaKey,
      control: e.ctrlKey,
      alt: e.altKey
    };
    log('要发送给傀儡端robot响应的数据为 ---> data:', data);
    emitRobotCommand('key', data);

    //todo 没法实现 win+x alt+tab 等快捷键,
    //  win 会直接弹出系统菜单 中断你下一个被连的按键
    //  https://stackoverflow.com/questions/44308471/disable-windows-key-in-electron
    //  上面这个连接里也没有办法 简而言之 无解
    //  electron全局快捷键注册也无法设置 返回值会为false
  }

  //鼠标移动
  const onMounsemove = (e) => {
    // log('window.onmousemove---:', e);
    const data = {
      video: getVideoBoundingClientRect(),
      ...getMousePosition(e)
    };

    // log('要发送给傀儡端robot响应的数据为 ---> data:', data);
    emitRobotCommand('mousemove', data);
  }
  video.onmousemove = throttle(onMounsemove, 125); //todo 使用节流的话 可能刚好被节流的是你鼠标停止的位置 这样控制鼠标和被控制鼠标永远就无法重合了。 换一种思路, 使用定时器定时发送鼠标现在的位置 (?)

  //鼠标按下
  video.onmousedown = function (e) {
    log('window.onmousedown---:', e);
    const data = {
      button: e.button,
      video: getVideoBoundingClientRect(),
      ...getMousePosition(e)
    }
    log('要发送给傀儡端robot响应的数据为 ---> data:', data);
    emitRobotCommand('mousedown', data);
  }

  //鼠标抬起
  video.onmouseup = function (e) {
    log('window.onmouseup---:', e);
    const data = {
      button: e.button,
      video: getVideoBoundingClientRect(),
      ...getMousePosition(e)
    }
    log('要发送给傀儡端robot响应的数据为 ---> data:', data);
    emitRobotCommand('mouseup', data);
  }

  //没撒必要
  // video.ondblclick = function(){}
};
